<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="分类名称" prop="categoryName">
        <el-input
          v-model="queryParams.categoryName"
          placeholder="请输入分类名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择状态" clearable>
          <el-option
            v-for="dict in dict.type.enable_flag"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['system:post:add']"
        >新增
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="info"
          icon="el-icon-sort"
          size="mini"
          @click="toggleExpand"
        >展开/折叠
        </el-button>
      </el-col>
      <!-- 右侧工具条 -->
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>
    <el-table
      :data="postList"
      style="width: 100%"
      row-key="categoryId"
      border
      v-if="reftable"
      :default-expand-all="defaultExpandAll"
      :tree-props="{children: 'children', hasChildren: 'hasChildren'}">
      <el-table-column
        prop="categoryId"
        label="父类ID"
        width="180">
      </el-table-column>
      <el-table-column
        prop="categoryName"
        label="分类名称"
        width="180">
      </el-table-column>
      <el-table-column
        prop="remark"
        label="备注">
      </el-table-column>
      <el-table-column
        prop="createBy"
        label="创建者">
      </el-table-column>
      <el-table-column label="创建时间" align="center" prop="createTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="状态" align="center" prop="status">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.enable_flag" :value="scope.row.status"/>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['system:post:edit']"
          >修改
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-circle-plus-outline"
            @click="handleAddChild(scope.row)"
            v-hasPermi="['system:post:edit']"
          >新增
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="父级分类" prop="categoryId">
          <treeselect
            v-model="form.categoryId"
            :options="deptOptions"
            :normalizer="deptNormalizer"
            placeholder="选择父级分类"
            :disabled="isParentDisabled"
          />
        </el-form-item>
        <el-form-item label="分类名称" prop="categoryName">
          <el-input v-model="form.categoryName" placeholder="请输入分类名称"/>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="form.status">
            <el-radio
              v-for="dict in dict.type.enable_flag"
              :key="dict.value"
              :label="dict.value"
            >{{ dict.label }}
            </el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入内容"/>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { add, selectById, treeV3, update } from "@/api/kobe/classification/classification";
import Treeselect from "@riophae/vue-treeselect"
import "@riophae/vue-treeselect/dist/vue-treeselect.css"

export default {
  name: "ClassificationIndex",
  dicts: ['enable_flag'],
  components: { Treeselect },
  data() {
    return {
      reftable: true,
      // 是否默认展开所有节点
      defaultExpandAll: false,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 分类表格数据
      postList: [],
      // 部门树选项
      deptOptions: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 是否禁用父级分类选择
      isParentDisabled: false,
      // 查询参数
      queryParams: {
        categoryName: undefined,
        status: undefined,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        categoryName: [
          { required: true, message: "分类名称不能为空", trigger: "blur" }
        ],
        parentId: [
          { required: true, message: "父级分类不能为空", trigger: "blur" }
        ]
      }
    }
  },
  //钩子函数
  created() {
    this.getList()
  },
  methods: {
    // 取消按钮操作
    cancel() {
      this.open = false
      this.reset()
    },
    /** 查询分类列表 */
    getList() {
      this.loading = true
      treeV3(this.queryParams).then(response => {
        // 处理树形数据，确保所有节点都有必要的属性
        this.postList = this.processTreeData(response)
        // 构建部门树选项
        this.deptOptions = this.buildDeptTree(this.postList)
        this.loading = false
      })
    },
    // 处理树形数据，确保所有节点都有必要的属性
    processTreeData(data) {
      return data.map(item => {
        // 确保每个节点都有必要的属性
        const processedItem = {
          categoryId: item.categoryId || item.id,
          categoryName: item.categoryName || item.label,
          parentId: item.parentId || "0",
          status: item.status || "0",
          remark: item.remark || "",
          createBy: item.createBy || "",
          createTime: item.createTime || null,
          children: item.children ? this.processTreeData(item.children) : []
        }
        return processedItem
      })
    },
    // 构建部门树
    buildDeptTree(data) {
      return data.map(item => {
        const node = {
          id: item.categoryId,
          label: item.categoryName,
          children: item.children && item.children.length > 0 ? this.buildDeptTree(item.children) : null
        }
        return node
      })
    },
    // 格式化部门树数据
    deptNormalizer(node) {
      return {
        id: node.id,
        label: node.label,
        children: node.children
      }
    },
    /** 转换分类数据结构 */
    normalizer(node) {
      // 处理children为空的情况
      if (node.children && !node.children.length) {
        delete node.children
      }
      return {
        // 映射原始节点的属性到treeselect需要的格式
        id: node.categoryId,
        label: node.categoryName,
        children: node.children
      }
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset()
      const categoryId = row.categoryId
      selectById(categoryId).then(response => {
        // 检查响应数据结构
        this.form = response.data
        this.open = true
        this.title = "修改知识分类"
        this.getList()
      })
    },
    /** 新增子分类按钮操作 */
    handleAddChild(row) {
      this.reset()
      // 设置父级分类为当前选中的分类
      this.form.parentId = row.categoryId
      this.open = true
      this.title = "添加子分类"
    },
    // 表单重置
    reset() {
      this.form = {
        categoryId: undefined,
        categoryName: undefined,
        parentId: "0",
        status: "0",
        remark: undefined
      }
      this.resetForm("form")
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm")
      this.handleQuery()
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset()
      this.open = true
      this.title = "添加知识分类"
      this.isParentDisabled = false
    },
    /** 切换展开/折叠 */
    toggleExpand() {
      // 切换表格状态，避免展开所有节点后再点击修改按钮导致表格刷新后展开所有节点
      this.reftable = false
      // 切换默认展开所有节点状态
      this.defaultExpandAll = !this.defaultExpandAll
      // 等待表格刷新完成后，切换表格状态为true
      this.$nextTick(() => {
        this.reftable = true
      })
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          // 确保parentId不为undefined
          if (this.form.parentId === undefined) {
            this.form.parentId = "0"
          }
          if (this.form.categoryId !== undefined) {

            // 修改分类
            update(this.form).then(response => {
              this.$modal.msgSuccess("修改成功")
              this.open = false
              this.getList()
            }).catch(error => {
              console.error('修改分类失败:', error)
              this.$modal.msgError("修改分类失败")
            })
          } else {
            // 新增分类
            add(this.form).then(response => {
              this.$modal.msgSuccess("新增成功")
              this.open = false
              this.getList()
            }).catch(error => {
              console.error('新增分类失败:', error)
              this.$modal.msgError("新增分类失败")
            })
          }
        }
      })
    }
  }
}
</script>

<style scoped lang="scss">
</style>
